<template>
  <page-layout>
    <a-spin :spinning="isLoading">
      <a-card class="mb-15">
        <div class="box-hor-end">
          <a-button type="primary" @click="handleSave">{{ t('button.save') }}</a-button>
        </div>
      </a-card>
      <a-card title="基础信息">
        <a-form ref="formRef" :model="formData" :label-col="labelCol">
          <a-row>
            <a-col :span="8">
              <a-form-item :label="t('course-manage.label.school')">
                <a-input v-model:value="formData.data.schoolCnName"
                         readonly
                         placeholder="请双击选择学校"
                         @dblclick="handleOpenSchoolModal('base')"
                />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item :label="t('course-manage.label.year')">
                <a-date-picker v-model:value="formData.data.particularYear"
                               mode="year"
                               class="w-100p"
                               format="yyyy年"
                               valueFormat="yyyy"
                               :open='yearPickShow'
                               @panelChange="handlePanelChange"
                               @openChange="handleOpenChange"
                />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item :label="t('course-manage.label.quarter')">
                <a-select v-model:value="formData.data.semester" placeholder="请选择">
                  <a-select-option v-for="item in dictLists.data[dictEnum.QUARTER]"
                                   :key="item.value"
                                   :value="item.value"
                  >
                    {{ item.label }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item :label="t('course-manage.label.timePeriod')">
                <a-range-picker v-model:value="formData.data.timePeriod" valueFormat="yyyy-MM-DD"/>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item :label="t('course-manage.label.project')">
                <a-input v-model:value="formData.data.projectName"
                         placeholder="请双击选择项目"
                         readonly
                         @dblclick="handleOpenProjectModal"
                />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item :label="t('course-manage.label.courseName')">
                <a-input v-model:value="formData.data.courseName" placeholder="请输入"/>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item :label="t('course-manage.label.courseCode')">
                <a-input v-model:value="formData.data.courseCode" placeholder="请输入"/>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item :label="t('course-manage.label.credit')">
                <a-input v-model:value="formData.data.credit" placeholder="请输入"/>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item :label="t('course-manage.label.courseType')">
                <a-select v-model:value="formData.data.courseType" placeholder="请选择">
                  <a-select-option v-for="item in dictLists.data[dictEnum.COURSE_TYPE]"
                                   :key="item.value"
                                   :value="item.value"
                  >
                    {{ item.label }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item :label="t('course-manage.label.courseBeforeCode')">
                <a-input v-model:value="formData.data.coursePastCode" placeholder="请输入"/>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item :label="t('course-manage.label.courseFirstOpenTime')">
                <a-date-picker v-model:value="formData.data.firstCourseStarttime"
                               valueFormat="yyyy-MM-DD"
                               type="date"
                               class="w-100p"
                />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item :label="t('course-manage.label.courseAuditTime')">
                <a-date-picker v-model:value="formData.data.courseLastReviewtime"
                               valueFormat="yyyy-MM-DD"
                               type="date"
                               class="w-100p"
                />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item :label="t('course-manage.label.courseLastOpenTime')" class="mb-0">
                <a-date-picker v-model:value="formData.data.courseLastOpentime"
                               valueFormat="yyyy-MM-DD"
                               type="date"
                               class="w-100p"
                />
              </a-form-item>
            </a-col>
          </a-row>
        </a-form>
      </a-card>
      <a-card title="SOR" class="mt-15">
        <a-form ref="sorFormRef" :model="formData.data">
          <a-row v-for="(sorItem, sorIndex) in formData.data.cbiSorList"
                 :key="sorIndex"
                 :gutter="16"
                 type="flex"
                 justify="space-between"
                 align="bottom"
          >
            <a-col :span="6">
              <a-form-item :label="t('course-manage.label.schoolName')"
                           :name="['cbiSorList', sorIndex, 'schoolName']"
                           :rules="requiredRules"
                           class="mb-0"
              >
                <a-input readonly
                         placeholder="请双击选择学校"
                         v-model:value="sorItem.schoolName"
                         @dblclick="handleOpenSchoolModal('sor', sorIndex)"
                />
              </a-form-item>
            </a-col>
            <a-col :span="5">
              <a-form-item :label="t('course-manage.label.courseCode')"
                           :name="['cbiSorList', sorIndex, 'courseCode']"
                           :rules="requiredRules"
                           class="mb-0"
              >
                <a-input v-model:value="sorItem.courseCode" :placeholder="placeHolder"/>
              </a-form-item>
            </a-col>
            <a-col :span="5">
              <a-form-item :label="t('course-manage.label.courseName')"
                           :name="['cbiSorList', sorIndex, 'courseName']"
                           :rules="requiredRules"
                           class="mb-0"
              >
                <a-input v-model:value="sorItem.courseName" :placeholder="placeHolder"/>
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item :label="t('course-manage.label.auditPassTime')"
                           :name="['cbiSorList', sorIndex, 'auditPassTime']"
                           :rules="requiredRules"
                           class="mb-0"
              >
                <a-date-picker v-model:value="sorItem.auditPassTime"
                               :placeholder="placeHolder"
                               type="date"
                               class="w-100p"
                />
              </a-form-item>
            </a-col>
            <a-col :span="2">
              <a-button v-if="sorIndex === 0" type="primary" ghost @click="addCourseItem">
                {{ t('button.add') }}
              </a-button>
              <a-button v-else type="danger" ghost @click="deleteCourseItem(sorIndex)">
                {{ t('button.delete') }}
              </a-button>
            </a-col>
          </a-row>
        </a-form>
      </a-card>
      <a-card title="课程描述" class="mt-15">
        <div class="box-ver-center">
          <div v-for="item in formData.data.files"
               :key="item.fileId"
               :style="{ backgroundImage: 'url(' + item.url + ')' }"
               class="thumb-item mb-8 mr-10"
          />
          <a-upload list-type="picture-card"
                    :showUploadList="false"
                    :customRequest="handleUpload"
          >
            <plus-outlined/>
            <div class="ant-upload-text">{{ t('button.upload') }}</div>
          </a-upload>
        </div>
        <div>
          <p>该图片主要显示于小程序</p>
          <p>支持jpg,png格式</p>
          <p>图片尺寸建议498✖️300,大小不超过500kb</p>
        </div>
        <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
          <img alt="缩略图" style="width: 100%" :src="previewImage"/>
        </a-modal>
        <TinyMCE v-model:value="formData.data.describe"/>
      </a-card>
    </a-spin>
  </page-layout>
  <BasicTableModal v-model:visible="schoolModal.show"
                   :columns="schoolModal.columns"
                   @selectUniversity="handleSelectSchool"
  />
  <BasicTableModal v-model:visible="projectModal.show"
                   :columns="projectModal.columns"
                   :title="projectModal.title"
                   :fetchAjax="page"
                   @selectUniversity="handleSelectProject"
  />
</template>

<script>
import TinyMCE from '@/component/tinymce'
import BasicTableModal from '@/component/basic-table-modal'
import { getBase64, isEmpty } from '@/tools/common'
import { upload } from '@/api/module/oss'
import { save, update, selectById } from '@/api/module/courseBaseInfo'
import { page } from '@/api/module/project'
import { reactive, ref, toRaw, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useI18n } from 'vue-i18n'
import { message } from 'ant-design-vue'
import { getDictByCodesReturnObj } from "@/tools/get-dict"
import dictEnum from "@/const/dict"
import moment from 'moment'

export default {
  name: 'course-base-info-add',
  components: {
    TinyMCE,
    BasicTableModal
  },
  setup() {
    const { t } = useI18n()
    const route = useRoute()
    const router = useRouter()
    const placeHolder = '请输入'
    const labelCol = { span: 10 }
    const formRef = ref(null)
    const sorFormRef = ref(null)
    const isLoading = ref(false)
    const yearPickShow = ref(false)
    const previewVisible = ref(false)
    const previewImage = ref('')
    const pageType = ref('add')
    const formData = reactive({
      data: {
        cbiSorList: [],
        describe: '',
        files: []
      }
    })

    const schoolModal = reactive({
      show: false,
      dataIndex: null,
      columns: []
    })

    const projectModal = reactive({
      show: false,
      title: '选择项目',
      columns: [
        { dataIndex: "schName", key: "schName", title: "合作学校" },
        { dataIndex: "projectName", key: "projectName", title: "项目名称" },
      ]
    })

    const requiredRules = [{ required: true, message: '请输入' }]

    const addCourseItem = () => formData.data.cbiSorList.push({
      schoolName: '',
      courseCode: '',
      courseName: '',
      auditPassTime: ''
    })
    const deleteCourseItem = sendIndex => formData.data.cbiSorList.splice(sendIndex, 1)

    const handlePreview = async (file) => {
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj)
      }

      previewImage.value = file.url || file.preview
      previewVisible.value = true
    }

    const handleCancel = () => previewVisible.value = false

    const handleUpload = data => {
      isLoading.value = true
      const ajaxFormData = new FormData()
      ajaxFormData.append('file', data.file)
      upload(ajaxFormData).then(res => {
        if (res.code === 500) {
          message.error({ content: '上传图片失败' })
        } else {
          const { path: url, id: fileId, remark, name } = res.data
          formData.data.files = [{ type: 'courseThumb', url, fileId, remark, name }]
        }
        isLoading.value = false
      }).catch(_ => {
        isLoading.value = false
      })
    }

    const handleChange = info => formData.data.files = info.fileList.filter(v => v.status !== 'error')

    const handleSave = async () => {
      await formRef.value.validate()
      await sorFormRef.value.validate()
      const courseBasicInformation = toRaw(formData.data)
      const { files, describe } = courseBasicInformation
      if (describe.length === 0) return message.error({ content: '请输入课程详情' })
      if (files.length === 0) return message.error({ content: '请上传课程封面图' })

      if (courseBasicInformation.timePeriod && courseBasicInformation.timePeriod.length === 2) {
        courseBasicInformation.periodStartMonth = courseBasicInformation.timePeriod[0]
        courseBasicInformation.periodEndMonth = courseBasicInformation.timePeriod[1]
      }

      delete courseBasicInformation.timePeriod

      let response, content = ''
      if (pageType.value === 'edit') {
        response = await update({ ...courseBasicInformation, id: route.query.id })
        content = '修改'
      } else {
        response = await save(courseBasicInformation)
        content = '新增'
      }

      if (response.code === 500) return message.error(`${content}失败`)
      message.success({
        content: `${content}成功`,
        onClose() {
          router.push('/university/course-base-info')
        }
      })
    }

    const handleOpenProjectModal = () => {
      projectModal.show = true
    }

    const handleOpenSchoolModal = (type, _index) => {
      schoolModal.show = true
      schoolModal.type = type
      if (type === 'sor') {
        schoolModal.dataIndex = _index
      }
    }

    const handleSelectSchool = data => {
      const { id: schId, schoolCnName } = data

      if (schoolModal.type === 'sor') {
        formData.data.cbiSorList[schoolModal.dataIndex].schoolName = schoolCnName
        formData.data.cbiSorList[schoolModal.dataIndex].schId = schId
        schoolModal.dataIndex = null
      } else {
        formData.data.schId = schId
        formData.data.schoolCnName = schoolCnName
      }

      schoolModal.type = null
    }

    const handleSelectProject = data => {
      formData.data.projectId = data.id
      formData.data.projectName = data.projectName
    }

    const handleOpenChange = status => {
      yearPickShow.value = status
    }

    const handlePanelChange = value => {
      formData.data.particularYear = moment(value).format('yyyy')
      yearPickShow.value = false
    }

    const dictLists = reactive({
      data: {}
    })

    onMounted(async () => {

      const isEdit = !isEmpty(route.query.id)
      pageType.value = isEdit ? 'edit' : 'add'

      if (isEdit) {
        const formResponse = await selectById({ id: route.query.id })
        formData.data = formResponse.data
        formData.data.timePeriod = [
          moment(Number(formResponse.data.periodStartMonth)).format('yyyy-MM-DD'),
          moment(Number(formResponse.data.periodEndMonth)).format('yyyy-MM-DD')
        ]
        if (formData.data.cbiSorList.length === 0) addCourseItem()
      } else {
        addCourseItem()
      }

      dictLists.data = await getDictByCodesReturnObj([
        dictEnum.FOLLOW_PROGRESS,
        dictEnum.COURSE_TYPE,
        dictEnum.QUARTER
      ])

      schoolModal.columns = [
        { dataIndex: "schoolCnName", key: "schoolCnName", title: "学校中文名" },
        { dataIndex: "schoolEnName", key: "schoolEnName", title: "学校英文名", },
        {
          dataIndex: "schFollowUpProgress",
          key: "schFollowUpProgress",
          title: "跟进进度",
          cellRender: (record, data) => {
            if (dictLists.data[dictEnum.FOLLOW_PROGRESS]) {
              const item = dictLists.data[dictEnum.FOLLOW_PROGRESS].find(v => v.value == data)
              return item ? item.label : '-'
            }
            return '-'
          }
        }
      ]
    })

    return {
      t,
      formData,
      previewImage,
      previewVisible,
      placeHolder,
      labelCol,
      requiredRules,
      formRef,
      sorFormRef,
      schoolModal,
      projectModal,
      isLoading,
      dictLists,
      dictEnum,
      yearPickShow,
      page,
      addCourseItem,
      deleteCourseItem,
      handlePanelChange,
      handleOpenChange,
      handleOpenSchoolModal,
      handleOpenProjectModal,
      handleSelectProject,
      handleSelectSchool,
      handlePreview,
      handleCancel,
      handleUpload,
      handleSave,
      handleChange
    }
  }
}
</script>

<style lang="less" scoped>
.thumb-item {
  width: 102px;
  height: 102px;
  background-size: cover;
  background-position: center center;
}
</style>
